package com.tl.wechat.pay.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tl.wechat.config.WeChatPayProperties;
import com.tl.wechat.pay.domain.WxPayInfo;
import com.tl.wechat.pay.utils.WXPayConstants;
import com.tl.wechat.pay.utils.WXPayUtil;

import java.util.Map;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.client.methods.HttpPost;



/**
 * 微信支付
 * @author 15110
 *
 */
@Service
public class WeChatPayService {
	
	
    private static final Logger log = LoggerFactory.getLogger(WeChatPayService.class);
    
    /**
     * 是否是沙箱环境
     */
    private boolean useSandbox;
    
    @Autowired
    private WeChatPayProperties weChatPayProperties;
    
    
    /**
     * 预下单
     */
    public Map<String, Object> createWXOrder(WxPayInfo wpi){
        try {
        	System.out.println("微信支付创建开始:-------------");
        	System.out.println("微信支付回调地址:-------------"+wpi.getNotifyUrl());
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("body",wpi.getBody());
            data.put("out_trade_no",wpi.getOutTradeNo());
            if(wpi.getTradeType().equals("JSAPI")){
                data.put("openid",wpi.getOpenId());
            }
            data.put("fee_type", "CNY");
            data.put("total_fee", Integer.valueOf(wpi.getTotalFee()));
            data.put("spbill_create_ip", wpi.getCliIp());
            data.put("notify_url", weChatPayProperties.getNotifyUrl()+"/wxPay/notifyOrder");
            data.put("trade_type", wpi.getTradeType());  // 此处指定为扫码支付
            Map<String, Object> resp = unifiedOrder(data);
            System.out.println("微信支付返回结果:-------------"+resp);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("微信支付失败:-------------"+e.getMessage());
            return null;
        }
    }
    

	/**
     * 作用：统一下单<br>
     * 场景：公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间，单位是毫秒
     * @param readTimeoutMs 读超时时间，单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, Object> unifiedOrder(Map<String, Object> reqData) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_UNIFIEDORDER_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.UNIFIEDORDER_URL_SUFFIX;
        }
        if(reqData.get("notifyUrl") != null) {
            reqData.put("notify_url",reqData.get("notifyUrl"));
        }
        // 根据商户API密钥生成签名
        reqData.put("appid", weChatPayProperties.getAppId());
        reqData.put("mch_id", weChatPayProperties.getMchId());
        reqData.put("nonce_str", WXPayUtil.generateNonceStr());
        reqData.put("sign", WXPayUtil.generateSignature(reqData,weChatPayProperties.getMchKey()));
        // 将所有参数(map)转xml格式
        String reqBody = WXPayUtil.mapToXml(reqData);
        System.out.println("微信支付组装xml:-------------"+reqBody);
        String result = null;//返回结果
        Map<String, Object> payMap = new HashMap<String, Object>();
        String unifiedorder_url = "https://"+WXPayConstants.DOMAIN_API+url;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(unifiedorder_url);
        httppost.setEntity(new StringEntity(reqBody, "UTF-8"));
        CloseableHttpResponse resp = httpclient.execute(httppost);
        try {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity,"UTF-8");
                System.out.println("微信支付回调数据:-------------"+result);
                if (result.indexOf(WXPayConstants.SUCCESS) != -1) {
                    Map<String, Object> map = WXPayUtil.xmlToMap(result);
                    payMap.put("package", "prepay_id=" + map.get("prepay_id"));// 预支付id
                    payMap.put("appId", weChatPayProperties.getAppId());
                    payMap.put("signType", WXPayConstants.MD5);
                    payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
                    payMap.put("nonceStr", WXPayUtil.generateNonceStr());
                    payMap.put("paySign", WXPayUtil.generateSignature(payMap,weChatPayProperties.getMchKey()));
                    payMap.put("orderId", reqData.get("out_trade_no").toString());
                }
            }
        } finally {
            resp.close();
        }
        return payMap;
    }
    
    
    


}
